<?php


namespace app\controller\coach;


use app\BaseController;
use app\common\ErrorCode;
use app\common\exception\ApiException;
use app\common\SmsCode;

use app\model\article\ArticleModel;
use app\model\coach\CoachMoneyDetailModel;
use app\model\coach\CoachWithdrawRecordModel;
use app\model\coach\UserCoachInviteModel;
use app\model\coach\UserCoachModel;
use app\model\partner\EscortMenuOrderModel;
use app\model\partner\EscortMenuReserveOrderModel;
use app\model\partner\FeedbackModel;
use app\model\partner\UserPartnerModel;
use app\model\school\SchoolModel;
use app\model\school\SchoolOrderModel;
use app\model\user\PartnerMoneyRecordModel;
use app\model\user\PartnerWithdrawRecordModel;
use app\model\user\UserEvaluateModel;
use app\model\user\UserModel;
use app\service\config\ConfigService;
use app\service\user\CoachMoneyDetailService;
use app\service\user\PartnerMoneyRecordService;
use app\service\user\UserPartnerService;
use app\service\utils\SmsService;
use app\service\utils\WeiXinOfficialService;
use app\service\utils\WeiXinPayService;
use app\service\utils\WeiXinService;
use app\validate\user\CoachLoginValidate;
use app\validate\user\PartnerLoginValidate;
use think\facade\Cache;
use think\facade\Db;
use zjkal\TimeHelper;

class UserController extends BaseController
{
    /**
     * 登录
     * @return \think\response\Json
     */
    public function login()
    {
        try {
            $data = $this->request->only(['mobile', 'sms_code'], 'param', 'trim');

            Validate(CoachLoginValidate::class)->check($data);

            // 使用模型查询用户信息
            $userInfo = UserCoachModel::where('mobile', $data['mobile'])->find();
            if (!$userInfo) {
                throw new ApiException('用户不存在');
            }
            if ($userInfo['status'] == 0) {
                throw new ApiException('账号被冻结');
            }
            SmsService::verifySms($data['mobile'], $data['sms_code'], SmsCode::APP_LOGIN);

            // 更新用户登录信息和生成token
            $token = random(200, 'all');
            $info = [
                'token' => $token,
                'token_valid_time' => time() + 86400,
            ];
            $userInfo->save($info);
            return $this->success(['token' => $token]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function getUserInfo()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $result = [
                'id' => $userInfo['id'],
                'mobile' => $userInfo['mobile'],
                'username' => $userInfo['username'],
                'avatar' => $userInfo['avatar'],
                'team' => $userInfo['team'],
                'edu_type' => $userInfo['edu_type'],
                'service_score' => $userInfo['service_score'],
                'money' => $userInfo['money'],
                'is_team_leader' => $userInfo['is_team_leader'],
                'openid' => $userInfo['openid'],
            ];
            // 驾校
            $result['school_name'] = SchoolModel::where('id', $userInfo['school_id'])->value('name');
            $result['service_tel'] = ConfigService::getConfigValue('service_tel');
            $userId = $userInfo['id'];
            // 已邀请学员
            if ($userInfo['is_team_leader']) {
                $coachIdArr = UserCoachModel::where('school_id', $userInfo['school_id'])->column('id');
                $inviteNum = UserModel::whereIn('coach_id', $coachIdArr)->count();
            } else {
                $inviteNum = UserModel::where('coach_id', $userId)->count();
            }
            $result['invite_user'] = $inviteNum;
            // 驾校学费
            if ($userInfo['is_team_leader']) {
                $schoolFee = SchoolOrderModel::whereIn('status', [2, 3, 4, 6])->where('school_id', $userInfo['school_id'])->sum('coach_amount');
            } else {
                $schoolFee = SchoolOrderModel::whereIn('status', [2, 3, 4, 6])->where('coach_id', $userInfo['id'])->sum('coach_amount');
            }
            $result['school_fee'] = $schoolFee;
            // 未结款学员
            if ($userInfo['is_team_leader']) {
                $noPayUser = SchoolOrderModel::whereIn('status', [2, 3, 6])->where('school_id', $userInfo['school_id'])->count();
            } else {
                $noPayUser = SchoolOrderModel::whereIn('status', [2, 3, 6])->where('coach_id', $userInfo['id'])->count();
            }
            $result['no_pay_user'] = $noPayUser;
            // 已结款学员
            if ($userInfo['is_team_leader']) {
                $payUser = SchoolOrderModel::whereIn('status', [4])->where('school_id', $userInfo['school_id'])->count();
            } else {
                $payUser = SchoolOrderModel::whereIn('status', [4])->where('coach_id', $userInfo['id'])->count();
            }
            $result['pay_user'] = $payUser;
            // 平台佣金
            if ($userInfo['is_team_leader']) {
                $totalAmount = SchoolOrderModel::whereIn('status', [2, 3, 4, 6])->where('school_id', $userInfo['school_id'])->sum('amount');
            } else {
                $totalAmount = SchoolOrderModel::whereIn('status', [2, 3, 4, 6])->where('coach_id', $userInfo['id'])->sum('amount');
            }
            $result['platform_fee'] = $totalAmount - $schoolFee;
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 获取团队信息
     * @return \think\response\Json
     */
    public function getTeamInfo()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $result = [
                'id' => $userInfo['id'],
                'mobile' => $userInfo['mobile'],
                'username' => $userInfo['username'],
                'avatar' => $userInfo['avatar'],
                'team' => $userInfo['team'],
                'is_team_leader' => $userInfo['is_team_leader'],
                'school_name' => SchoolModel::where('id', $userInfo['school_id'])->value('name'),
            ];
            $where = [];
            $userId = $userInfo['id'];
            if ($userInfo['is_team_leader']) {
                $coachIdArr = UserCoachModel::where('pid', $userId)->column('id');
                array_push($coachIdArr, $userId);
                $where[] = ['coach_id', 'in', $coachIdArr];
            } else {
                $where[] = ['coach_id', '=', $userId];
            }

            // 总服务学员
            $result['service_user'] = SchoolOrderModel::where($where)
                ->whereIn('status', [3, 4, 6])
                ->group('user_id')
                ->count();
            // 当前学员
            $result['current_user'] = SchoolOrderModel::where($where)
                ->where('status', 3)
                ->group('user_id')
                ->count();
            // 待结算订单
            $result['no_settle'] = SchoolOrderModel::where($where)
                ->where('status', 3)
                ->count();
            // 已结算订单
            $result['has_settle'] = SchoolOrderModel::where($where)
                ->where('status', 4)
                ->count();
            // 合计教练总数
            if ($userInfo['is_team_leader'] == 0) {
                $result['total_coach'] = 0;
            } else {
                $result['total_coach'] = UserCoachModel::where('pid', $userId)->count();
            }
            // 待认证
            if ($userInfo['is_team_leader'] == 0) {
                $result['not_pay_coach'] = UserCoachInviteModel::where('user_id', $userId)->where('status', 0)->count();
            } else {
                $result['not_pay_coach'] = UserCoachInviteModel::where('invite_user_id', $userId)->where('status', 0)->count();
            }
            // 已开通
            if ($userInfo['is_team_leader'] == 0) {
                $result['pay_coach'] = 0;
            } else {
                $result['pay_coach'] = UserCoachModel::where('pid', $userId)->where('is_pay', 1)->count();
            }
            // 待交保证金
            if ($userInfo['is_team_leader'] == 0) {
                $result['pay'] = 0;
            } else {
                $result['pay'] = UserCoachModel::where('pid', $userId)->where('is_pay', 0)->count();
            }


            // 科目一成员
            $result['one'] = SchoolOrderModel::where($where)->where('progress', 2)->group('user_id')->count();
            // 科目二成员
            $result['two'] = SchoolOrderModel::where($where)->where('progress', 3)->group('user_id')->count();
            // 科目三成员
            $result['three'] = SchoolOrderModel::where($where)->where('progress', 4)->group('user_id')->count();
            // 科目四成员
            $result['four'] = SchoolOrderModel::where($where)->where('progress', 5)->group('user_id')->count();
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 转化率
     * @return \think\response\Json
     */
    public function getConversionRatio()
    {
        try {
            // 计算教练的转化率
            $userInfo = $this->request->middleware('userInfo');
            $ratioInfo = $userInfo['ratio'];
            return $this->success($ratioInfo);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 微信授权
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function wxScope()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');

            $code = $this->request->param('code', '', 'trim');

            $weiXinOfficialService = new WeiXinOfficialService();
            $user = $weiXinOfficialService->wxAuth($code);

            $userInfo->openid = $user->getId();
            $userInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 提现
     * @return \think\response\Json
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function withdraw()
    {
        Db::startTrans();
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');

            $amount = $this->request->param('amount', 0, 'int');
            $name = $this->request->param('name', '', 'trim');
            $day = date('j');
            if (!in_array($day, [6, 16, 26])) {
                throw new ApiException('每月6号，16号，26号才能提现');
            }
            if ($amount <= 0) {
                throw new ApiException('提现金额错误');
            }

            $openId = $userInfo['openid'];
            if (!$openId) {
                throw new ApiException('用户未授权', ErrorCode::SCOPE_LOGIN);
            }

            $userInfo = UserCoachModel::lock('lock in share mode')->where('id', $userId)->find();
            $before = $userInfo['money'];
            if ($before < $amount) {
                throw new ApiException('余额不足');
            }

            $orderSn = createOrderSn('coach_money_detail', 'order_sn', 'TX');

            // 提现记录
            $coachWithdrawRecordModel = new CoachWithdrawRecordModel();
            $coachWithdrawRecordModel->user_id = $userId;
            $coachWithdrawRecordModel->money = $amount;
            $coachWithdrawRecordModel->order_sn = $orderSn;
            $coachWithdrawRecordModel->receive = $amount;
            $coachWithdrawRecordModel->type = 2;
            $coachWithdrawRecordModel->status = 0;
            $coachWithdrawRecordModel->save();

            $moneyRecordService = new CoachMoneyDetailService();
            $type = PartnerMoneyRecordService::WITHDRAW;
            $title = $moneyRecordService->getTypeText($type);
            $moneyRecordService->createLog($title, $userId, $type, $amount, 0, $orderSn, '');

//            $weiXinPayService = new WeiXinPayService();
//            $weiXinPayService->toBalance($orderSn, $openId, $name, intval($amount * 100), '学车教练提现');
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 钱包明细
     * @return \think\response\Json
     */
    public function getMoneyRecord()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');

            $list = PartnerMoneyRecordModel::where('user_id', $userInfo['id'])
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success(['money' => $userInfo['money'], 'list' => $list]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 分享二维码
     * @return \think\response\Json
     */
    public function getUserQrcode()
    {
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');
            if (!$userInfo['qrcode']) {
                $weiXinService = new WeiXinService();
                $path = $weiXinService->getCoachQrcode('/pages/tabbar/my?type=1&scene=' . $userId, $userId);
                $userInfo->qrcode = $path;
                $userInfo->save();
            } else {
                $path = $userInfo['qrcode'];
            }
            return $this->success(['qrcode' => $path, 'url' => '']);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 教练上传学员评价
     * @return \think\response\Json
     */
    public function evaluate()
    {
        try {
            $userId = $this->request->middleware('userId');
            $img = $this->request->param('img', '', ['trim', 'htmlspecialchars']);

            $userExamineRecordModel = new  UserEvaluateModel();
            $userExamineRecordModel->user_id = 0;
            $userExamineRecordModel->coach_id = $userId;
            $userExamineRecordModel->type = 1;
            $userExamineRecordModel->score = 0;
            $userExamineRecordModel->img = $img;
            $userExamineRecordModel->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 团队成员信息
     * @return \think\response\Json
     */
    public function getTeamUser()
    {
        try {
            $userId = $this->request->middleware('userId');

            // 教练数
            $coachCount = UserCoachModel::where('pid', $userId)->count();
            // 总学员
            $userCount = SchoolOrderModel::where('accept_uid', $userId)->whereIn('status', [2, 3, 4, 6])->count();
            // 教学中
            $userStudyCount = SchoolOrderModel::where('accept_uid', $userId)->whereIn('status', [3, 6])->count();
            // 本月分配学员
            $thisMonthAssignUserCount = SchoolOrderModel::where('accept_uid', $userId)
                ->where('coach_id', '>', 0)
                ->whereIn('status', [2, 3, 4, 6])
                ->whereBetweenTime('assign_time', strtotime(date('Y-m')), strtotime(date('Y-m-t')))
                ->count();
            // 本月全部学员
            $thisMonthUserCount = SchoolOrderModel::where('accept_uid', $userId)
                ->whereIn('status', [2, 3, 4, 6])
                ->whereBetweenTime('assign_time', strtotime(date('Y-m')), strtotime(date('Y-m-t')))
                ->count();
            $data = [
                'coach_count' => $coachCount,// 教练数
                'user_count' => $userCount,// 总学员
                'user_study_count' => $userStudyCount,// 教学中
                'this_month_assign_user_count' => $thisMonthAssignUserCount,// 本月分配学员
                'this_month_user_count' => $thisMonthUserCount,// 本月全部学员
            ];
            return $this->success($data);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 团队成员
     * @return \think\response\Json
     */
    public function getTeamUserList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $search = $this->request->param('search', '', 'trim');
            $where = [];
            $where[] = ['pid', '=', $userId];
            if ($search != '') {
                $where[] = ['username|mobile', 'like', "%{$search}%"];
            }
            $list = UserCoachModel::where($where)
                ->field('id,username,mobile,avatar,is_pay,create_time')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                // 总学员
                $totalUserCount = SchoolOrderModel::where('coach_id', $v['id'])
                    ->whereIn('status', [3, 4])
                    ->count();
                $v['total_order'] = $totalUserCount;
                // 未启动
                $noStartUserCount = SchoolOrderModel::where('coach_id', $v['id'])
                    ->where('status', 3)
                    ->where('progress', 0)
                    ->count();
                $v['no_start_order'] = $noStartUserCount;
                // 已结束
                $endUserCount = SchoolOrderModel::where('coach_id', $v['id'])
                    ->where('status', 4)
                    ->count();
                $v['end_order'] = $endUserCount;
                // 教学中
                $userStudyCount = SchoolOrderModel::where('coach_id', $v['id'])
                    ->where('status', 3)
                    ->where('progress', '>', 0)
                    ->count();
                $v['study_order'] = $userStudyCount;
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 邀请列表
     * @return \think\response\Json
     */
    public function getInviteUserList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $list = UserModel::where('coach_id', $userId)
                ->field('id,username,mobile,avatar')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $schoolId = SchoolOrderModel::where('user_id', $v['id'])->whereIn('status', [2, 3, 4])->value('school_id', 0);
                $v['school'] = SchoolModel::where('id', $schoolId)->value('name', '');
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}